package com.rxy.rabbitmq.api.exchange.direct;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.QueueingConsumer.Delivery;
/**
 * direct Exchange
 * @author ruoxiyuan
 *
 */
public class Consumer4DirectExchange {

	public static void main(String[] args) throws Exception {
		
		//1 创建ConnectionFactory
        ConnectionFactory connectionFactory = new ConnectionFactory() ;  
        connectionFactory.setHost("192.168.43.157");
        connectionFactory.setPort(5672);
		connectionFactory.setVirtualHost("/");
		// 1.设置是否自动重连(网络闪断时)      2.每3秒重连一次
        connectionFactory.setAutomaticRecoveryEnabled(true);
        connectionFactory.setNetworkRecoveryInterval(3000);
        //2 创建Connection
        Connection connection = connectionFactory.newConnection();
        //3 创建Channel
        Channel channel = connection.createChannel();  
		//4 声明
		String exchangeName = "test_direct_exchange";
		String exchangeType = "direct";
		String queueName = "test_direct_queue";
		String routingKey = "test.direct";
		
		//表示声明了一个交换机
		//参数分别为：name,type,durable,autoDelete,internal,arguments
		channel.exchangeDeclare(exchangeName, exchangeType, true, false, false, null);
		//表示声明了一个队列
		//参数分别为：name,durable,exclusive,autoDelete,arguments
		channel.queueDeclare(queueName, false, false, false, null);
		//建立一个绑定关系(exchange和queue)
		channel.queueBind(queueName, exchangeName, routingKey);
		
		//细节一：同一个队列可以绑定多个值
		channel.queueBind(queueName, exchangeName, "666");
		//细节二：不同队列可以绑定相同的RoutingKey
		String queueName2 = "test_direct_queue2";
		channel.queueDeclare(queueName2, false, false, false, null);
		channel.queueBind(queueName2, exchangeName, routingKey);
		
        QueueingConsumer consumer = new QueueingConsumer(channel);
        //参数：队列名称、是否自动ACK、Consumer
        channel.basicConsume(queueName, true, consumer);
        //监听多个队列
        channel.basicConsume(queueName2, true, consumer);
        //5 循环获取消息  
        while(true){  
            //获取消息，如果没有消息，这一步将会一直阻塞  
            Delivery delivery = consumer.nextDelivery();  
            String msg = new String(delivery.getBody());    
            System.out.println("收到消息：" + msg);  
        } 
	}
}
